<template>
	<view class="home-container">
		<!-- Tab切换栏 -->
		<view class="tab-bar">
			<view class="tab-item" :class="{ active: activeTab === 'city' }" @click="switchTab('city')">城际线路</view>
			<view class="tab-item" :class="{ active: activeTab === 'rural' }" @click="switchTab('rural')">城乡线路</view>
		</view>

		<view class="form-card">
			<!-- 当前位置信息 -->
			<view class="current-position" v-if="false">
				<image class="position-icon" src="/static/released/current-locat.png" mode="aspectFill"></image>
				<text>{{ currenPosition }}</text>
			</view>
			<view class="divider"></view>

			<!-- 出发地 -->
			<view class="form-item" @click="showLocationPicker('departure')">
				<text class="label">出发地</text>
				<view class="value">
					<text :class="{ 'has-value-color': formData.departure }">{{ formData.departure || '请选择' }}</text>
					<image src="/static/personalCenter/details.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="divider"></view>

			<!-- 目的地 -->
			<view class="form-item" @click="showLocationPicker('destination')">
				<text class="label">目的地</text>
				<view class="value">
					<text :class="{ 'has-value-color': formData.destination }">{{ formData.destination || '请选择' }}</text>
					<image src="/static/personalCenter/details.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="divider"></view>

			<!-- 途径 -->
			<view class="form-item textarea-item">
				<text class="label">途径</text>
				<textarea
					class="textarea"
					placeholder="示例：路过环城高速、城南高速"
					maxlength="100"
					v-model="formData.route"
					@input="countRouteChars"
					@focus="handleRouteFocus"
					:style="{ color: formData.route ? '#0b1f20' : '#999999' }"
				></textarea>
				<text class="char-count">{{ routeCharCount }}/100</text>
			</view>
			<view class="divider"></view>
			<!-- 出发时间 -->
			<view class="form-item" @click="showTimePicker = true">
				<text class="label">出发时间</text>
				<view class="value">
					<text :class="{ 'has-value-color': formData.start_time }">{{ formData.start_time || '请选择出发时间' }}</text>
					<image src="/static/personalCenter/details.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="divider"></view>
			<!-- 出行车辆 -->
			<view class="form-item" @click="showCarPicker">
				<text class="label">出行车辆</text>
				<view class="value">
					<text :class="{ 'has-value-color': formData.vehicle }">{{ formData.vehicle || '例:别克GL8' }}</text>
					<image src="/static/personalCenter/details.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="divider"></view>

			<!-- 可订座位数 -->
			<view class="form-item" @click="showSeatPicker">
				<text class="label">可订座位数</text>
				<view class="value">
					<text :class="{ 'has-value-color': formData.seats }">{{ formData.seats || '请选择座位数' }}</text>
					<image src="/static/personalCenter/details.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="divider"></view>

			<!-- 单座价格 -->
			<view class="form-item" @click="openPriceSelector">
				<text class="label">单座价格</text>
				<view class="value">
					<text :class="{ 'has-value-color': formData.price }">{{ formData.price || '请选择价格' }}</text>
					<image src="/static/personalCenter/details.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="divider"></view>
			<view class="suggest-price" v-if="true">
				<text style="color: #ff7937">系统建议价：</text>
				{{ recommendedPrice.rec_price || 0 }}/座
			</view>
			<view class="suggest-price" v-if="false" style="color: #ff3f39">系统暂未开放该线路，请重新选择线路</view>

			<!-- 备注 -->
			<view class="form-item textarea-item">
				<text class="label">备注</text>
				<textarea
					class="textarea"
					placeholder="示例：顺路上下，请预定后电话确认"
					maxlength="100"
					v-model="formData.remarks"
					@input="countRemarkChars"
					:style="{ color: formData.remarks ? '#0b1f20' : '#999999' }"
				></textarea>
				<text class="char-count">{{ remarkCharCount }}/100</text>
			</view>
			<view class="divider"></view>

			<!-- 手机号码 -->
			<view class="form-item">
				<text class="label">手机号码</text>
				<view class="value">
					<input
						class="input"
						v-model="formData.phone"
						placeholder="请输入手机号码"
						maxlength="11"
						placeholder-class="placeholder"
						:style="{ color: formData.phone ? '#0b1f20' : '#999999' }"
					/>
					<image class="edit-icon" src="/static/home/safe-edit.png" @click.stop="changeIphone"></image>
				</view>
			</view>
			<view class="divider"></view>

			<!-- 提交按钮 -->
			<view class="submit-btn" @click="submitForm">发布行程信息</view>

			<!-- 底部协议信息 -->
			<view class="footer-agreement-warps">
				<image class="check-icon" :src="`/static/personalCenter/${checkName}.png`" mode="aspectFill" @click="handleCheck"></image>
				<text>已阅读并同意</text>
				<text class="agreement-content" style="color: #ff7937" @click="confirmAgreement">《合乘协议》</text>
			</view>
			<view class="auth-sub-info">
				<view>温馨提示:</view>
				<view>请保证实际出行车辆、实收价格、实际路线等与发布出行信息一致，若被乘客投诉，一经核实将按照情节严重程度进行扣除诚信值或封禁账号处罚</view>
			</view>
		</view>
		<!-- 车辆选择器 -->
		<u-picker :show="isShowCarPicker" :columns="[columnsCar]" keyName="label" closeOnClickOverlay @confirm="confirmCarPicker" @cancel="closeCarPicker"></u-picker>
		<!-- 座位选择器 -->
		<u-picker :show="isShowSeats" :columns="[columnsSeats]" keyName="label" closeOnClickOverlay @confirm="confirmSeatsPicker" @cancel="closeSeatsPicker"></u-picker>
		<!-- 合乘协议 -->
		<agreementPopup :showAgreement="showAgreement" @update:visible="updateVisible" />
		<!-- 时间选择器 -->
		<dateTimePicker :show="showTimePicker" @update:show="showTimePicker = $event" @change="onTimeChange" />
		<!-- 价格选择器 -->
		<PriceSelector
			:show="showPriceSelector"
			:recommended-price="Number(recommendedPrice.rec_price) || 0"
			:current-price="Number(formData.price) || 0"
			@confirm="onPriceConfirm"
			@cancel="onPriceCancel"
		/>
		<share-flex-vue></share-flex-vue>
	</view>
</template>

<script>
import moment from 'moment';
import agreementPopup from '../common/carpooleAgreementPopup';
import dateTimePicker from '../common/dateTimePicker.vue';
import PriceSelector from '@/components/PriceSelector.vue';
import { checkLogin } from '@/utils/auth';
import { isEmpty } from '@/utils/util';
export default {
	components: { agreementPopup, dateTimePicker, PriceSelector },
	data() {
		return {
			checkName: 'auth-gou', // auth-gou
			isChecked: true,
			selectedStartLocation: null,
			selectedEndLocation: null,
			currenPositionType: '',
			showAgreement: false,
			isShowCarPicker: false,
			isShowSeats: false,
			activeTab: 'city', // 默认激活城际线路
			formData: {
				start_time: '',
				start_time_value: '',
				departure: '', // 出发点
				destination: '', // 目的地
				route: '', // 途径
				vehicle: '', // 车辆
				car_id: null,
				seats: '', // 座位数
				price: '', // 单价
				remarks: '', // 备注
				phone: '' // 手机号码
			},
			routeCharCount: 0,
			remarkCharCount: 0,
			showTimePicker: false,
			showPriceSelector: false,
			currenPosition: '定位中...',
			columnsCar: [],
			columnsSeats: [],
			recommendedPrice: {},
			authInfo: null,
			timer: null
		};
	},
	// 显示页面时刷新数据 -
	onShow() {
		this.getCarData();
		this.getAuthInfoData();
	},
	onLoad() {
		// 监听地点选择结果
		uni.$on('locationSelected', (result) => {
			this.setLocationFu(result);
		});
		this.fetchUserInfo();
	},
	methods: {
		changeIphone() {
			uni.navigateTo({
				url: '/pages/personalCenter/account/modifyPhone'
			});
		},
		onTimeChange(e) {
			this.$nextTick(function () {
				this.$set(this.formData, 'start_time', `${e.date} ${moment(e.dateTime).format('HH:mm')}`);
				this.$set(this.formData, 'start_time_value', e.dateTime);
			});
			this.closeDateTimePicker();
		},
		updateTime() {
			this.timer = setInterval(() => {
				this.currenPosition = '';
			}, 1000);
		},
		async fetchUserInfo() {
			try {
				const res = await this.$http.get('/h5/user/me');
				uni.setStorageSync('userInfo', res.data.user);
				this.formData.phone = res.data.user.phone;
				this.getAuthInfoData();
			} catch (error) {}
		},
		// 获取认证信息
		async getAuthInfoData() {
			try {
				const data = await this.$http.get('/h5/user/carowner/authInfo');
				let resData = data.data;
				this.authInfo = resData;
				uni.setStorageSync('is_auth', resData && resData.status == 1 ? true : false);

				if (!this.authInfo) {
					uni.showModal({
						title: '提示',
						content: '请先进行车主认证之后，才能发布',
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								setTimeout(() => {
									// 使用 Storage 传递参数
									uni.setStorageSync('switchTabParams', {
										id: uni.getStorageSync('is_auth'),
										from: 'released',
										timestamp: Date.now()
									});
									uni.switchTab({
										url: `/pages/personalCenter/index`
									});
								}, 50);
							} else if (res.cancel) {
								uni.showToast({
									title: '进行车主认证之后，才能发布',
									icon: 'none'
								});
							}
						}
					});
				} else {
					if (this.authInfo.status != 1) {
						uni.showModal({
							content: this.authInfo.status == 0 ? '正在审核中' : '审核驳回',
							confirmText: '去查看',
							success: function (res) {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/personalCenter/auth/auditSate'
									});
								} else if (res.cancel) {
									uni.switchTab({
										url: '/pages/home/index'
									});
								}
							}
						});
					}
				}
			} catch (error) {}
		},
		onTabItemTap(item) {
			if (item.text == '车主发布') {
				if (!checkLogin()) {
					return;
				}
			}
		},
		handleCheck() {
			this.isChecked = !this.isChecked;
			this.checkName = this.isChecked ? 'auth-gou' : 'auth-quan';
		},
		validatePhoneNumber(phone) {
			const reg = /^1[3-9]\d{9}$/;
			return reg.test(phone);
		},
		// 选择的出发地 目的地
		setLocationFu(data) {
			if (this.currenPositionType === 'departure') {
				this.selectedStartLocation = data;
				if (data.fullAddress) {
					this.formData.departure = data.fullAddress;
				} else {
					this.formData.departure = `${data.city.name}.${data.address}`;
				}
			} else {
				this.selectedEndLocation = data;
				if (data.fullAddress) {
					this.formData.destination = data.fullAddress;
				} else {
					this.formData.destination = `${data.city.name}.${data.address}`;
				}
			}
			if (!isEmpty(this.selectedStartLocation) && !isEmpty(this.selectedEndLocation)) {
				this.getRecommendedPrice(this.selectedStartLocation.city.id, this.selectedEndLocation.city.id);
			}
		},
		// 获取系统推荐价格
		async getRecommendedPrice(sid, eid) {
			let params = {
				start_id: sid,
				end_id: eid
			};
			try {
				const data = await this.$http.post('/h5/user/line/getLineRecommendPrice', params);

				if (isEmpty(data.data)) {
					uni.showToast({
						title: '您所选的线路暂未开放,请选择其他线路',
						icon: 'none',
						duration: 5000
					});
					return;
				}
				this.recommendedPrice = data.data;
				this.formData.price = data.data.rec_price;
			} catch (error) {}
		},

		closeDateTimePicker() {
			this.showTimePicker = false;
			this.formData.start_time = '';
		},

		// 出行车辆相关
		async getCarData() {
			if (!checkLogin()) {
				return;
			}
			try {
				const data = await this.$http.get('/h5/user/carowner/myCars');
				this.columnsCar =
					data.data &&
					data.data.map((i) => {
						return {
							label: i.brand_model,
							id: i.id,
							seats: i.seats
						};
					});
			} catch (error) {}
		},
		confirmCarPicker(e) {
			this.formData.vehicle = e.value[0].label;
			this.formData.car_id = e.value[0].id;
			this.columnsSeats = [];
			for (let index = 1; index < 5; index++) {
				const element = `${index}座`;
				let obj = {
					label: element,
					value: index
				};
				this.columnsSeats.push(obj);
			}
			this.closeCarPicker();
		},
		closeCarPicker() {
			this.isShowCarPicker = false;
		},
		// 座位数相关
		closeSeatsPicker() {
			this.isShowSeats = false;
		},
		confirmSeatsPicker(e) {
			this.formData.seats = e.value[0].value;
			this.closeSeatsPicker();
		},
		updateVisible() {
			this.showAgreement = false;
		},
		confirmAgreement() {
			this.showAgreement = true;
		},
		// 切换Tab
		switchTab(tab) {
			this.activeTab = tab;
		},
		showLocationPicker(type) {
			this.currenPositionType = type;
			// 使用增强版地点选择器
			uni.navigateTo({
				url: `/pages/common/location-picker-enhanced?type=${type}&activeTab=${this.activeTab}`
			});
		},
		showCarPicker() {
			this.isShowCarPicker = true;
		},
		showSeatPicker() {
			if (this.columnsSeats.length == 0) {
				uni.showToast({
					title: '请选择出行车辆',
					icon: 'none'
				});
				return;
			}
			this.isShowSeats = true;
		},
		// 显示价格选择器
		openPriceSelector() {
			if (this.isLocationEmpty()) {
				uni.showModal({
					title: '提示',
					content: '请先选择出发地目的地',
					showCancel: false,
					confirmText: '确定'
				});
				return;
			}
			if (!this.recommendedPrice.rec_price) {
				uni.showToast({
					title: '请先选择出发地目的地获取建议价',
					icon: 'none'
				});
				return;
			}
			this.showPriceSelector = true;
		},
		// 价格选择器确认 - 与u-picker保持一致
		onPriceConfirm(e) {
			this.formData.price = e.value[0].value;
			this.showPriceSelector = false;
		},
		// 价格选择器取消 - 与u-picker保持一致
		onPriceCancel() {
			this.showPriceSelector = false;
		},
		countRouteChars(e) {
			this.routeCharCount = e.detail.value.length;
		},
		countRemarkChars(e) {
			this.remarkCharCount = e.detail.value.length;
		},
		isLocationEmpty() {
			return !this.formData.departure || !this.formData.destination;
		},

		handleRouteFocus() {
			if (this.isLocationEmpty()) {
				uni.showModal({
					title: '提示',
					content: '请先选择出发地目的地',
					showCancel: false,
					confirmText: '确定'
				});
			}
		},
		async submitForm() {
			if (!this.formData.start_time) {
				uni.showToast({
					title: '请选择出发时间',
					icon: 'none'
				});
				return;
			}
			if (!this.formData.departure) {
				uni.showToast({
					title: '请选择出发地',
					icon: 'none'
				});
				return;
			}
			if (!this.formData.destination) {
				uni.showToast({
					title: '请选择目的地',
					icon: 'none'
				});
				return;
			}
			if (!this.formData.vehicle) {
				uni.showToast({
					title: '请选择出行车辆',
					icon: 'none'
				});
				return;
			}
			if (!this.formData.seats) {
				uni.showToast({
					title: '请选择预定座位数',
					icon: 'none'
				});
				return;
			}
			if (!this.formData.price) {
				uni.showToast({
					title: '请选择单座价格',
					icon: 'none'
				});
				return;
			}
			if (!this.validatePhoneNumber(this.formData.phone)) {
				uni.showToast({
					title: '请填写正确的手机号码',
					icon: 'none'
				});
				return;
			}
			if (!this.isChecked) {
				uni.showToast({
					title: '请阅读并同意合乘协议',
					icon: 'none'
				});
				return;
			}

			// 判断价格是否大于系统建议价
			if (Number(this.formData.price) > Number(this.recommendedPrice.rec_price) + Number(this.recommendedPrice.allow_price_wave)) {
				// 计算总价格
				let totalPrice =
					(Number(this.recommendedPrice.rec_price) + Number(this.recommendedPrice.allow_price_wave)) * Number(this.columnsSeats[this.columnsSeats.length - 1].value);
				let maxSeats = Math.floor(totalPrice / Number(this.formData.price));
				if (Number(this.formData.seats) > maxSeats) {
					uni.showModal({
						title: '温馨提示',
						content: `顺风车不能以盈利为目的，您的发布价格大于平台建议价，本次最多能发布${maxSeats}个座位。`,
						confirmText: '继续发布',
						cancelText: '修改价格',
						success: (res) => {
							if (res.confirm) {
								if (Number(this.formData.seats) > maxSeats) {
									this.formData.seats = maxSeats;
								}
								this.doSaveTrip();
							} else {
								this.getRecommendedPrice(this.selectedStartLocation.id, this.selectedEndLocation.id);
							}
						}
					});
					return;
				}
			}
			this.doSaveTrip();
		},
		async doSaveTrip() {
			let params = {
				type: this.activeTab === 'city' ? 2 : 1, // 类型：1=城乡线路，2=城际线路 必填
				start_time: this.formData.start_time_value, // 出发时间 必填
				start_id: this.selectedStartLocation.city.id, // 起点id 必填
				start_title: this.selectedStartLocation.address.title, // 出发点详细地址 必填
				end_id: this.selectedEndLocation.city.id, // 终点id 必填
				end_title: this.selectedEndLocation.address.title, // 终点详细地址 必填
				approach: this.formData.route, // 途径 非必填
				car_id: this.formData.car_id, // 车辆id 必填
				current_seats: this.formData.seats, // 可预定座位数 必填
				unit_price: this.formData.price, // 单座价格 必填
				remark: this.formData.remarks, // 备注 非必填
				phone: this.formData.phone
			};

			try {
				const res = await this.$http.post(`/h5/user/line/add/`, params);
				this.clearFormData();
				uni.showToast({
					title: '发布成功',
					icon: 'success'
				});
				setTimeout(() => {
					uni.switchTab({
						url: `/pages/home/index`
					});
				}, 1000);
			} catch (error) {}
		},
		// 清除表单
		clearFormData() {
			this.formData = {};
			this.selectedStartLocation = {};
			this.selectedEndLocation = {};
			this.columnsSeats = [];
			this.columnsCar = [];
			this.isShowCarPicker = false;
			this.isShowSeats = false;
			this.isChecked = true;
			this.checkName = 'auth-gou';
			this.routeCharCount = 0;
			this.remarkCharCount = 0;
			this.showTimePicker = false;
			this.showPriceSelector = false;
			this.showAgreement = false;
			this.activeTab = 'rural';
			this.currenPositionType = '';
		},
		// 导航到指定页面
		navigateTo(url) {
			uni.navigateTo({
				url: url
			});
		}
	},
	onUnload() {
		uni.$off('locationSelected');
		// 页面卸载时清除定时器
		if (this.timer) {
			clearInterval(this.timer);
			this.timer = null;
		}
	}
};
</script>

<style scoped lang="scss">
/* tab样式 */
.tab-bar {
	display: flex;
	height: 100rpx;
	line-height: 100rpx;
	text-align: center;
	border-bottom: 2rpx solid #eee;
	background: #ffffff;
	border-radius: 16rpx 16rpx 0 0;
	padding-top: 24rpx;
}

.tab-item {
	flex: 1;
	font-size: 32rpx;
	color: #999999;
	line-height: 84rpx;
	text-align: center;
}

.tab-item.active {
	position: relative;
	font-weight: 500;
	font-size: 36rpx;
	color: #ff7937;
	line-height: 84rpx;
}

.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 144rpx;
	height: 8rpx;
	background-color: #ff7937;
	border-radius: 16rpx 16rpx 16rpx 16rpx;
}

.tab-content {
	background: #ffffff;
	margin-bottom: 40rpx;
}

.form-card {
	background-color: #fff;
	border-radius: 16rpx;
	margin: 20rpx 26rpx;
}

.current-position {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-weight: 500;
	font-size: 32rpx;
	color: #0b1f20;
	line-height: 48rpx;
	padding: 36rpx 0 36rpx 32rpx;
	display: flex;
	align-items: center;
}

.position-icon {
	width: 32rpx;
	height: 32rpx;
	margin-right: 12rpx;
}

.form-item {
	padding: 36rpx 0 36rpx 40rpx;
	display: flex;
}

.label {
	display: block;
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-weight: 500;
	font-size: 32rpx;
	color: #0b1f20;
	line-height: 48rpx;
	width: 190rpx;
	margin-right: 12rpx;
}

.value {
	flex: 1;
	display: flex;
	align-items: center;
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-size: 28rpx;
	color: #999999;
	line-height: 42rpx;
	justify-content: space-between;
}

.value image {
	width: 28rpx;
	height: 28rpx;
	margin-left: auto;
}

.value .input {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-size: 32rpx;
	color: #666666;
}

.placeholder {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-size: 28rpx;
	color: #999999;
}

.divider {
	height: 2rpx;
	background-color: #eee;
	margin: 0 40rpx;
}

.textarea-item {
	position: relative;
	display: flex;
	flex-direction: column;
}

.textarea {
	height: 160rpx;
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-weight: 400;
	font-size: 28rpx;
	color: #999999;
	line-height: 42rpx;
	width: 100%;
	box-sizing: border-box;
	margin-top: 16rpx;
}

.char-count {
	position: absolute;
	right: 40rpx;
	bottom: 16rpx;
	font-size: 28rpx;
	color: #999;
}

.suggest-price {
	font-size: 28rpx;
	color: #999999;
	margin-top: 16rpx;
	padding-left: 40rpx;
}

.verified {
	color: #07c160;
	font-size: 32rpx;
}

.edit-icon {
	width: 32rpx;
	height: 32rpx;
	margin-left: 6rpx;
}

.submit-btn {
	background: linear-gradient(90deg, #ff3f39 0%, #ff7937 100%);
	border-radius: 16rpx;
	padding: 24rpx 0;
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-weight: 500;
	font-size: 36rpx;
	color: #ffffff;
	line-height: 54rpx;
	text-align: center;
	margin: 40rpx 26rpx;
}

.auth-sub-info {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-size: 24rpx;
	color: #999999;
	line-height: 48rpx;
	margin: 20rpx 40rpx 36rpx 40rpx;
	padding-bottom: 34rpx;
}

.footer-agreement-warps {
	display: flex;
	align-items: center;
	padding-left: 40rpx;
}

.check-icon {
	width: 40rpx;
	height: 40rpx;
	margin-right: 20rpx;
}

.footer-agreement-warps text {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-size: 28rpx;
	color: #0b1f20;
	line-height: 54rpx;
}

.form-item {
	.has-value-color {
		font-size: 32rpx;
		color: #0b1f20;
	}

	image {
		padding-right: 20rpx;
	}
}
</style>
